package com.qianya.weishi_server.controller;

import io.jsonwebtoken.Claims;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * Created by admin
 */
public abstract class BaseController {
    protected HttpSession session;
    protected HttpServletRequest request;
    protected HttpServletResponse response;
    protected ModelMap model;

    @ModelAttribute
    public void init(HttpSession session, HttpServletRequest request, HttpServletResponse response, ModelMap model) {
        this.session = session;
        this.request = request;
        this.response = response;
        this.model = model;
    }

    /**
     * 获取用户信息，只有通过TOKEN验证的接口才能通过此方法获取
     * @return
     */
    protected Claims getPrincipal(){
        return (Claims)request.getAttribute("CLAIMS");
    }

    /**
     * 添加Flash消息
     *
     * @param messages
     */
    protected void addMessage(RedirectAttributes redirectAttributes,
                              String... messages) {
        StringBuilder sb = new StringBuilder();
        for (String message : messages) {
            sb.append(message).append(messages.length > 1 ? "<br/>" : "");
        }
        redirectAttributes.addFlashAttribute("message", sb.toString());
    }

}
